package cn.xdwanj.config

import org.springframework.web.WebApplicationInitializer
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext
import org.springframework.web.filter.CharacterEncodingFilter
import org.springframework.web.servlet.DispatcherServlet
import javax.servlet.ServletContext

class SpringInit : WebApplicationInitializer {

  override fun onStartup(servletContext: ServletContext) {
    // 创建Spring容器(web特别版), 并注册, 这里就不需要
    /*
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     */
//    val xmlWebContext = XmlWebApplicationContext()
    val context = AnnotationConfigWebApplicationContext().apply { register(SpringRootConfig::class.java) }

    servletContext.apply {
      // 添加前端控制器
      addServlet("DispatcherServlet", DispatcherServlet(context)).apply {
        addMapping("/")
        setLoadOnStartup(1) // 设置加载优先级
      }
    }.apply {
      // 加载 Spring 的编码过滤器
      addFilter("/*", CharacterEncodingFilter().apply {
        encoding = "UTF-8"
        setForceEncoding(true)
      })
    }
  }
}